<?php
/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2016/9/12
 * Time: 15:10
 */

namespace app\models;


use app\librarys\Tools;

class Pay
{
    /**
     * 得到新订单号
     * @return  string
     */
    private function build_payOrder_no($pre = '')
    {

        mt_srand((double)microtime() * 1000000);

        /* PHPALLY + 年月日小时分秒 + 6位随机数 */
        return $pre . date('YmdHis') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }

    public static function getOrder($order_code)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_order where code=:order_code');
        $cmd->bindValue(':order_code', $order_code);
        return $cmd->queryOne();
    }

    /**
     * 现金换积分  下支付订单
     * @param $type
     * @param $order_code
     * @param $integral
     * @return string  返回支付订单号
     * @throws \yii\db\Exception
     */
    public static function addPayIntegralRecord($type, $order_code, $integral)
    {
        $total_fee = self::calcCash($integral) * 100;
        $out_trade_no = self::build_payOrder_no($type);
        $id = Tools::db_uuid();
        //t_order_cash_payment_record
        $cmd = \Yii::$app->db->createCommand('insert into t_order_cash_payment_record
       (id,out_trade_no,order_code,`type`,total_fee,integral,status,create_datetime) VALUES
        (:id,:out_trade_no,:order_code,:type,:total_fee,:integral,0,now())');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':out_trade_no', $out_trade_no);
        $cmd->bindValue(':order_code', $order_code);
        $cmd->bindValue(':type', $type);
        $cmd->bindValue(':total_fee', $total_fee);
        $cmd->bindValue(':integral', $integral);

        $cmd->execute();
        return ['out_trade_no' => $out_trade_no, 'id' => $id];
    }

    /**通过支付订单号 ,返回支付记录
     * @param $out_trade_no
     * @return array|false
     */
    public static function getPayIntegralRecord($out_trade_no)
    {
        $cmd = \Yii::$app->db->createCommand('select p.*,o.institution_code,u.id as user_id
     from t_order_cash_payment_record p, t_order o ,t_user u
        where o.code=p.order_code and o.user_id=u.id and p.out_trade_no=:out_trade_no');
        $cmd->bindValue(':out_trade_no', $out_trade_no);
        return $cmd->queryOne();

    }

    public static function endPayIntegralRecord($out_trade_no, $trade_no)
    {

        $item = self::getPayIntegralRecord($out_trade_no);
        if($item['status']=='1'){
            return true;///已经修改过了
        }
        if ($item == false) {
            // throw new \Exception("没有发现支付订单数据");
            return false;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //修改支付记录状态
            $cmd = \Yii::$app->db->createCommand('update t_order_cash_payment_record set status=1,trade_no=:trade_no where out_trade_no=:out_trade_no');
            $cmd->bindValue(':out_trade_no', $out_trade_no);
            $cmd->bindValue(':trade_no', $trade_no);
            $cmd->execute();
            //增加用户积分
            $cmd = \Yii::$app->db->createCommand('update t_user  set integral=integral+:integral where id=:user_id');
            $cmd->bindValue(':integral', $item['integral']);
            $cmd->bindValue(':user_id', $item['user_id']);
            $cmd->execute();
            //增加用户积分log
            $cmd = \Yii::$app->db->createCommand('insert into t_user_integral_record  (id,user_id,integral,record_type,origin_id,create_datetime,remark)
             VALUES (uuid(),:user_id,:integral,6,:origin_id,now(),null)');
            $cmd->bindValue(':integral', $item['integral']);
            $cmd->bindValue(':user_id', $item['user_id']);
            $cmd->bindValue(':origin_id', $item['id']);
            $cmd->execute();

            // 处理机构及其所有上级机构的帐
            $cmd = \Yii::$app->db->createCommand('select code_tree from t_institution where code=:institutionCode');
            $cmd->bindValue(':institutionCode', $item['institution_code']);
            $codeTree = $cmd->queryScalar();
            $institutionCodes = str_split($codeTree, 8);
            foreach ($institutionCodes as $institutionCode) {
                //增加机构账户余额
                $cmd = \Yii::$app->db->createCommand('update t_institution_account set balance=balance+:total_fee where institution_code=:institution_code');
                $cmd->bindValue(':total_fee', $item['total_fee'] / 100);
                $cmd->bindValue(':institution_code', $institutionCode);
                $cmd->execute();
                //增加机构账户余额 log
                $cmd = \Yii::$app->db->createCommand('insert into t_institution_account_record  (id,institution_code,amount,record_type,origin_id,create_datetime,remark)
             VALUES (uuid(),:institution_code,:amount,4,:origin_id,now(),null)');
                $cmd->bindValue(':amount', $item['total_fee'] / 100);
                $cmd->bindValue(':institution_code', $institutionCode);
                $cmd->bindValue(':origin_id', $item['id']);
                $cmd->execute();
            }

            // 添加订单现金支付备注
            $cmd = \Yii::$app->db->createCommand('UPDATE t_order SET pay_remark=:payRemark WHERE `code`=:orderCode');
            $cmd->bindValue(':payRemark', "现金支付￥" . $item['total_fee'] / 100);
            $cmd->bindValue(':orderCode', $item['order_code']);
            $cmd->execute();

            $transaction->commit();
            //修改为回调时候完成混合支付订单 todo:???是否能全部加入事物，这样就能保证一个支付对应一个订单.没有考虑清楚
            $orderInfo = MallFrontEnd::getOrderByCode($item['order_code']);
            $re = MallFrontEnd::payOrder($item['user_id'], $orderInfo['id']);//支付订单
//            file_put_contents('./debug.txt',$re);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return false;
        }
        return true;
    }

    //计算积分换算现金 单位:元
    public static function calcCash($integral)
    {
        $integral_rate = Mall::getCurrentInstitutionIntegralRate();
        return round(($integral / $integral_rate), 2);
    }

    /**获取支付订单标题
     * @param $orderCode
     * @param int $maxLength
     * @return string
     */
    public static function getOrderSubject($orderCode, $maxLength = 35)
    {
        $sql = "select group_concat(goods_name separator ';') subject,t2.integral from t_order_goods t1,t_order t2
         where t2.code=:orderCode and t1.order_id=t2.id";
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':orderCode', $orderCode);
        $result = $cmd->queryOne();
        $subject = $result['subject'];
        $ext_subject = '';
        if (mb_strlen($subject) > $maxLength) {
            $ext_subject = '...';
        }
        $subject = mb_substr($subject, 0, $maxLength - 4, 'utf-8');//截取头5个字
        $subject = $subject . $ext_subject;
        return $subject;
    }
}